<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { wallpaperCategoriesPage } from '@/api'
import { getSmartPageNumbers, getEllipsisStatus } from '@/utils/pagination.js'

const router = useRouter()

// 响应式数据
const wallpaperList = ref([]) // 壁纸列表
const currentPage = ref(1) // 当前页码
const totalPages = ref(1) // 总页数
const loading = ref(false) // 加载状态
const failedImages = ref(new Set()) // 记录加载失败的图片ID

// 获取热门排行数据
const fetchHotData = async (page = 1) => {
  loading.value = true
  try {
    const params = {
      page: page,
      pageSize: 21,
      type: 1, // 静态壁纸
      heat: 1 // 最热
    }

    const response = await wallpaperCategoriesPage(params)
    if (response.code === 200) {
      wallpaperList.value = response.data.records || []
      totalPages.value = Math.ceil(response.data.total / 21) || 1
      currentPage.value = page
    } else {
      console.error('获取热门排行数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取热门排行数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    fetchHotData(currentPage.value - 1)
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    fetchHotData(currentPage.value + 1)
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 跳转到指定页
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value && page !== currentPage.value) {
    fetchHotData(page)
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 计算分页显示的页码
const visiblePages = computed(() => {
  return getSmartPageNumbers(currentPage.value, totalPages.value, 5)
})

// 计算省略号状态
const ellipsisStatus = computed(() => {
  return getEllipsisStatus(currentPage.value, totalPages.value, visiblePages.value)
})

// 处理图片加载失败
const handleImageError = (imageId) => {
  failedImages.value.add(imageId)
}

// 打开壁纸详情页面
const openWallpaperDetail = (item, index) => {
  router.push(`/wallpaper/${item.id}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHotData(1)
})
</script>

<template>
  <div class="hottest-ranking">
    <!-- 壁纸展示区域 -->
    <div class="wallpaper-section">
      <h3 class="section-title">
        热门排行
      </h3>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <!-- 壁纸列表 -->
      <div v-else class="wallpaper-grid">
        <div 
          v-for="(item, index) in wallpaperList" 
          :key="index"
          class="wallpaper-item"
          @click="openWallpaperDetail(item, index)"
          v-show="!failedImages.has(item.id)"
        >
          <div class="image-container">
            <img 
              :src="item.url" 
              :alt="item.name"
              @error="handleImageError(item.id)"
              class="wallpaper-image"
            />
            <div class="image-overlay">
              <div class="image-info">
                <h3 class="image-title">{{ item.name }}</h3>
                <div class="image-details">
                  <span class="image-category">{{ item.classify || '未分类' }}</span>
                  <span class="image-resolution">{{ item.type === 1 ? '静态' : '动态' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页区域 -->
    <div v-if="totalPages > 1" class="pagination-section">
      <div class="pagination">
        <button 
          @click="prevPage" 
          :disabled="currentPage <= 1"
          class="pagination-btn"
          :class="{ disabled: currentPage <= 1 }"
        >
          上一页
        </button>
        
        <div class="page-numbers">
          <!-- 第一页按钮 -->
          <button
            v-if="ellipsisStatus.showStart"
            @click="goToPage(1)"
            class="page-btn"
            :class="{ active: currentPage === 1 }"
          >
            1
          </button>
          
          <!-- 前省略号 -->
          <span v-if="ellipsisStatus.showStart" class="page-ellipsis">...</span>
          
          <!-- 页码按钮 -->
          <button 
            v-for="page in visiblePages" 
            :key="page"
            @click="goToPage(page)"
            class="page-btn"
            :class="{ active: page === currentPage }"
          >
            {{ page }}
          </button>
          
          <!-- 后省略号 -->
          <span v-if="ellipsisStatus.showEnd" class="page-ellipsis">...</span>
          
          <!-- 最后一页按钮 -->
          <button
            v-if="ellipsisStatus.showEnd"
            @click="goToPage(totalPages)"
            class="page-btn"
            :class="{ active: currentPage === totalPages }"
          >
            {{ totalPages }}
          </button>
        </div>
        
        <button 
          @click="nextPage" 
          :disabled="currentPage >= totalPages"
          class="pagination-btn"
          :class="{ disabled: currentPage >= totalPages }"
        >
          下一页
        </button>
      </div>
      
      <div class="pagination-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页，总计 {{ wallpaperList.length }} 张图片
      </div>
    </div>
  </div>
</template>

<style scoped>
.hottest-ranking {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
}

/* 壁纸展示区域样式 */
.wallpaper-section {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  margin: 0 30px 20px;
  padding: 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .section-title {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 40px;
    text-align: center;
    color: #2c3e50;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background: linear-gradient(90deg, #3498db, #2ecc71);
      border-radius: 2px;
    }
  }
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 壁纸网格 */
.wallpaper-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  max-width: 1250px;
  margin: 0 auto;
}

.wallpaper-item {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.wallpaper-item:hover {
  transform: translateY(-8px) scale(1.02);
}

.image-container {
  position: relative;
  width: 100%;
  height: 280px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  background: #f8fafc;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.wallpaper-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.wallpaper-item:hover .image-container {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
}

.wallpaper-item:hover .wallpaper-image {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.wallpaper-item:hover .image-overlay {
  opacity: 1;
}

.image-info {
  .image-title {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 8px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .image-details {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .image-category,
  .image-resolution{
    font-size: 12px;
    padding: 2px 6px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
    backdrop-filter: blur(4px);
  }
}

/* 分页区域样式 */
.pagination-section {
  background: #fff;
  border-radius: 12px;
  padding: 30px 20px;
  margin: 0 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.pagination-btn {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  background: #fff;
  color: #374151;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.pagination-btn:hover:not(.disabled) {
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
}

.pagination-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-ellipsis {
  padding: 8px 12px;
  color: #666;
  font-weight: 500;
}

.page-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #d1d5db;
  background: #fff;
  color: #374151;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.page-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
}

.page-btn.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: #fff;
}

.pagination-info {
  text-align: center;
  color: #6b7280;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .wallpaper-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .hottest-ranking {
    padding: 0;
  }
  
  .wallpaper-section {
    margin: 0 16px 16px;
    padding: 20px 16px;
  }
  
  .wallpaper-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
  
  .image-container {
    height: 240px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .wallpaper-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .wallpaper-section {
    margin: 0 12px 12px;
    padding: 16px 12px;
  }
}
</style>